package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entify.OrderDetail;
import com.itheima.reggie.entify.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 实现支付按钮功能，并生成订单
     *
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {
        ordersService.submit(orders);
        return R.success("订单生成成功");
    }

    /**
     * 分页查询订单
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R userPage(Integer page, Integer pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        ordersService.page(pageInfo);
        List<Orders> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        List<OrdersDto> collect = records.stream().map(orders -> {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders, ordersDto);

            //订单明细信息
            LambdaQueryWrapper<OrderDetail> qw = new LambdaQueryWrapper<>();
            qw.eq(OrderDetail::getOrderId, ordersDto.getNumber());
            List<OrderDetail> details = orderDetailService.list(qw);
            ordersDto.setOrderDetails(details);
            return ordersDto;
        }).collect(Collectors.toList());
        Map map = new HashMap();
        map.put("total", total);
        map.put("records", collect);
        return R.success(map);
    }

    /**
     * 订单明细接口
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, Long number) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> qw = new LambdaQueryWrapper<>();
        qw.eq(number != null, Orders::getNumber, number);
        qw.orderByDesc(Orders::getOrderTime);
        ordersService.page(pageInfo, qw);
        return R.success(pageInfo);
    }
}
